#include "ring_buffer.h"

ringbuffer_type ringbuffer_init(rb_p rb, ringbuffer_data_type *buf, ringbuffer_type len) {
    if ((rb == 0) || (len == 0)) {
        return 0;
    }
    rb->len = len;
    rb->in = 0;
    rb->out = 0;
    rb->dat = buf;
    return rb->len;
    
}

ringbuffer_type ringbuffer_push_char(rb_p rb, ringbuffer_data_type *buf) {

    if (!rb) {
        return 0;
    }
    if (!buf) {
        return 0;
    }
    rb->dat[rb->in] = *buf;
    rb->in += 1;
    if (rb->in >= rb->len) {
        rb->in = 0;
    }
    return 1;
}

ringbuffer_type ringbuffer_pop_char(rb_p rb, ringbuffer_data_type *buf) {
    if (!rb) {
        return 0;
    }
    if (!buf) {
        return 0;
    }

    if (rb->out == rb->in) {
        return 0;
    }
    *buf = rb->dat[rb->out];
    rb->out += 1;

    if (rb->out >= rb->len) {
        rb->out = 0;
    }
    return 1;
}


ringbuffer_type ringbuffer_push_chars(rb_p rb, ringbuffer_data_type *buf, ringbuffer_type len) {
    for (int i = 0; i < len; i++) {
        if (!ringbuffer_push_char(rb, &buf[i]))
            return 0;
    }
    return len;
}


rb_p     ringbuffer_create(int size){
    
    int ret=0;
    
    rb_p buf=rb_malloc(sizeof(__ring_buffer)+size);
    if(buf)
    {
        ret=ringbuffer_init(buf,(ringbuffer_data_type *)&buf[1],size);
    }
    
    if(ret!=size){
        rb_free(buf);
        return NULL;
    }
    return buf;
}

void ringbuffer_destory(rb_p rb){
    if(rb){
        rb_free(rb);
    }
}


